<?php
class UserBook extends Zend_Db_Table_Abstract {
	
	protected $_primary = 'id';
	protected $_name = 'user_book';
	
	protected $_referenceMap = array (
    'User' => array (
        'columns' => 'user_id', 
        'refTableClass' => 'User', 
        'refColumns' => 'id' 
    ),
    'Book' => array (
        'columns' => 'book_id', 
        'refTableClass' => 'Book', 
        'refColumns' => 'id' 
    )
    );
	
    /**
     * Find by id.
     * 
     * @param $id
     */
    public function findById($id) {
    	return $this->find($id)->current();
    }
    
	/**
	 * Add/Update entry to user book.
	 * 
	 * @param $data
	 * @return return added user book id
	 */
	public function addOrUpdateUserBook($data) {
		$obj = new UserBook();
		$obj = $obj->findByBookAndUser($data["book_id"], $data["user_id"]);
		if (empty($obj)) {
			$obj = $this->createRow($data);
			$id = $obj->save();
			return $id;
		} else {
			$obj->condition = $data['condition'];
			$obj->usage = $data['usage'];
			$obj->note = $data['note'];
			$obj->modified = $data['modified'];
			if (isset($data['status'])) {
				$obj->status = $data['status'];
			}
			$obj->save();
			return $obj->id;
		}
	}
	
	/**
	 * Update user book status.
	 * 
	 * @param $book
	 * @param $user
	 * @param $status
	 */
	public function updateBookStatus($book, $user, $status) {
		$userBook = Book::getUserBook($book, $user);
		if (isset($userBook)) {
			$userBook->status = $status;
			$userBook->save();
		}
	}
	
	/**
	 * Find user book by given book and user, it should only return one entry.
	 * 
	 * @param $criteria
	 * @return user book object
	 */
	public function findByBookAndUser($book_id, $user_id) {
		$select = $this->select()
		->where('user_id=?', $user_id)->where('book_id=?', $book_id);
		return $this->fetchRow($select);
	}
	
	/**
	 * Return book.
	 * 
	 * @param $userBook
	 */
	public static function getBook($userBook) {
		return $userBook->findParentRow("Book");
	}
	
    /**
     * Return user.
     * 
     * @param $userBook
     */
    public static function getUser($userBook) {
        return $userBook->findParentRow("User");
    }
}
?>